// this file requires jquery



function generalLoadQuery (q, url, bl,prefixIn,useSpecificPrefix, biov_domain) {
	// Needed global variables: prefix

	var prefix = prefixIn;
	perform_freebase_read(
			url,
			q,
			function (msg) {
				var val = null;
				val = msg.result[0];
		            if (!val) return;

				// Obtain all of the companies from the list:
				var valList = msg.result;
				var numVals = valList.length;
				//alert(numVals);
				var colIndex1 = Math.floor(numVals/3);
				var colIndex2 = Math.floor(numVals*2/3);
				var colIndex3 = numVals - (colIndex1 + colIndex2);

				if (bl == false) {
						$("#list1 li").remove();
						$("#list2 li").remove();
						$("#list3 li").remove();
				}

				for (var i in valList) {
					if(useSpecificPrefix){

						var types = valList[i]['a:type'];

						

						var isTherapeutic = 0;

						for (var j in types) {

							var temp = types[j];

							var temp2 = (temp == biov_domain+"bv_therapeutic") 

							if  (temp2){

								isTherapeutic = 1;

							}

						}

						var w = '';

						if(isTherapeutic) {

							prefix = 'therapeutic'

						} 

						else {

							prefix = 'product'

						}			

					}

									

				    var w = prefix + valList[i].name;

					var h = '<li><a href="' + create_bvr_topic_href(prefix, valList[i].id) + '">' + valList[i].name + '</a></li>';

					

			     if (valList.length <= 20) { 

			    	 $("#list1").append(h);

			     } else { 

				     if(i < colIndex1){

				        	$("#list1").append(h); 

				        }

				     else if(i > colIndex1 && i < colIndex2){

				        	$("#list2").append(h); 

				        }

				     else{

				        	$("#list3").append(h); 

						}

				}

				}		

			},

		    function(msg){}

		);

}



function letterArray(queryParameters, prefix,useSpecificPrefix) {

	var alphabet = new Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','#');

	var numbers = new Array('1','2','3','4','5','6','7','8','9','0');

	var q = '';



	for (var i in alphabet) {

		var sort1 = '"sort":"name",';

		q  = '	{"query":[{'+ queryParameters +',' + sort1 + '"name~=":"^' + alphabet[i] + '*"}]}';

		

		queries.push(q);
		if (i == 8 || i == 17) { 

			var a = '<a id="letter" href="#" onClick="javascript:loadLetter(' + i + ',/'+ prefix +'/,'+useSpecificPrefix+');">' + alphabet[i] + '</a><br/>';
		} else {
			var a = '<a id="letter" href="#" onClick="javascript:loadLetter(' + i + ',/'+ prefix +'/,'+useSpecificPrefix+');">' + alphabet[i] + '</a>';

		}

		$("#alphabet_list").append(a);

	}

	return queries;

}

function getTitleName(prefix) {
	
	var titleVals = ['Analysis','Companies','Diseases','Products','Research Groups','Technologies','VC Firms'];
	var titleName = '';
	
	if (prefix == 'analysis') {
		titleName = titleVals[0];
	} else if (prefix == 'company') {
		titleName = titleVals[1];
	} else if (prefix == 'disease') {
		titleName = titleVals[2];
	} else if (prefix == 'product') {
		titleName = titleVals[3];
	} else if (prefix == 'researchgroup') {
		titleName = titleVals[4];
	} else if (prefix == 'technology') {
		titleName = titleVals[5];
	} else if (prefix == 'vcfirm') {
		titleName = titleVals[6];
	}
	return titleName;
	
}




function loadLetter(num,prefix,useSpecificPrefix) {
	
	prefix = parsePrefix(prefix.toString());
	var titleName = getTitleName(prefix);
	var bl = new Boolean(false);	

	var url = "http://www.freebase.com/api/service/mqlread";

	var q = queries[num];

	generalLoadQuery(q, url, bl, prefix,useSpecificPrefix);
	var alphabet = new Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','#');
	var sortTitle = '<h3 id="header3">' + titleName +': ' + alphabet[num] + '</h3>';
	$("#header3").remove();
	$("#sort_title").append(sortTitle);

}

function parsePrefix(s){
	var prefix = s.split('/');
	if(prefix.length == 3){  // That we had to surround the prefix by / /
		return prefix[1];
	} else {
		return prefix[0];
	}
}


function sortList(queryParameters, prefix, useSpecificPrefix) {

	var q = '';
	var titleName = getTitleName(prefix);
	if (prefix == 'company') {
		var ts = '<option>Sort ' + titleName + ' by:</option>';
		$("#list_sort").append(a);
		var compArray = [];                
        var sortOrder = ['(desc)','(asc)'];
        compSortArray = new Array('revenue','operating_income','market_capitalization','net_income','number_of_employees');
        var neg = '';
        var i = 0;
        for (var j in compSortArray) {
        	for (var k in sortOrder) {
        		if (k == 0) {
        			neg = '-';
        		} else {
        			neg = '';
        		}
                		if (compSortArray[j] != 'number_of_employees') {
                			compArray.push('[{"/business/company/'+compSortArray[j]+'":[{"amount":null,"currency":null}],"name":null,"sort":"'+neg+'/business/company/'+compSortArray[j]+'.amount","type":"/base/bioventurist/science_or_technology_company"}]');
                		} else {
                			 compArray.push('[{"/business/company/'+compSortArray[j]+'":[{"number":null,"source":null,"year":null}],"limit":1000,"name":null,"sort":"'+neg+'/business/company/'+compSortArray[j]+'.number","type":"/base/bioventurist/science_or_technology_company"}]');
                		}	
            q  = '	{"query":'+compArray[i]+'}';
			sortQueries.push(q);

			var tl = compSortArray[j].replace(/_/g,' ') + ' ' + sortOrder[k];
			titles.push(tl);
			var a = '<option onClick="javascript:loadSort(' + i + ',' + prefix + ',' + useSpecificPrefix + ');">' + tl +'</option>';
		
			$("#list_sort").append(a);
			i = i + 1;


       		}
       }
                
	}
}



function loadSort(num,prefix,useSpecificPrefix) {

	var bl = new Boolean(false);	
	var titleName = getTitleName(prefix);
	var url = "http://www.freebase.com/api/service/mqlread";
	var q = sortQueries [num];
	generalLoadQuery(q, url, bl, prefix,useSpecificPrefix);	
	var sortTitle = '<h3 id="header3">' + titleName + ' sorted by:' + ' ' + titles[num] + '</h3>';
	$("#header3").remove();
	$("#sort_title").append(sortTitle);
	document.getElementById('list_sort').selectedIndex = 0; 	
}

var ext;
var pre;
var spre;

 
function getFiltProps(prefix, useSpecificPrefix) {
	 
	 if (prefix == 'analysis') { 
	 	ext = "??";
	 } else if (prefix == 'company') { 
	 	ext = '/science_or_technology_company';	 	
	 } else if (prefix == 'disease') { 
	 	ext = '/bv_medical_condition';
	 } else if (prefix == 'product') { 
	 	ext = '/bv_product'; 
	 } else if (prefix == 'researchgroup') { 
	 	ext = '/bv_research_group';
	 } else if (prefix == 'technology') { 
	 	ext = '/bv_technology_class';
	 } else if (prefix == 'vcfirm') { 
	 	ext = '??';
	 } 	
	 pre = prefix;
	 spre = useSpecificPrefix;
	 readProps();	  
}


var gvArr = [];
var gvNme = [];

function readProps() { 
		gvArr = [];
		
		
		var b,c;
		var n = 0;
	 	var q = '{"query": [{"id":"/base/bioventurist'+ext+'","properties":[{"id":null,"name":null}],"type":"/type/type"}]}'; 
	 	var url = "http://www.freebase.com/api/service/mqlread";
		if (n !=1) {
		   	perform_freebase_read( url, q, 
		 	function (msg) { 
		 		var val = null;
		 		val = msg.result[0]; 
		 		if (!val) return; 
		 		var valList = msg.result; 
		 		var valProps = valList[0].properties;	 		
		 		var numVals = valProps.length;	 	 					
				for (var i in valProps) { 				
					b = valProps[i].id;
					gvArr.push(b);
					c = valProps[i].name;
					gvNme.push(c);
					var f = '<option onClick="javascript:getVals('+i+');">' + c +'</option>';
					$("#filtProps").append(f);
					}
				}, 
				function(msg){} 
				);
				n = 1;
		}				
} 
				
function getVals(w) {
	
	ps = [];
 	listResults = [];
	lsNm = [];
	
	var b = gvArr[w];
	var q = '{"query": [{"'+b+'":[{"id":null,"name":null}],"type":"/base/bioventurist'+ext+'"}]}'; 
	var url = "http://www.freebase.com/api/service/mqlread"; 
	var rt = '/base/bioventurist'+ext; 
	perform_freebase_read( url, q, 
	function (msg) {  
		var val = msg.result[0]; 
		if (!val) return; 
		var valList = msg.result; 
		var numVals = valList.length;				
		var valNames = [];
		var valNames2 = [];
		for (var f in valList) {
			var tl = valList[f][b];
			for (var g in tl) {
				if (tl[g].name != "") {
					valNames.push(tl[g].name);
				}
			}
		} 
		
	valNames.sort();
	valNames2 = valNames.unique();
	
	listFilters(b,valNames2,w);
	}, 
	function(msg){} 
	);
	
}

var ps = [];
var listResults = [];
var lsNm = [];

function listFilters(b,valNames2,w) {
	
		ps.push(b);
	
	for (var j in valNames2) {
		if (valNames2[j] != '') {
			var lsLen = listResults.length;
			var bval = '<li><a href="#" onclick="javascript:loadFiltResults('+ lsLen + ',' + j +','+w+');">'+valNames2[j]+'</a></li>';
			listResults.push(bval);
			lsNm.push(valNames2[j]);
		}
	}
	listResults.pop();
	
	var sortTitle = '<h3 id="header3">Please select a filter value from list below</h3>';
	$("#header3").remove();
	$("#sort_title").append(sortTitle);	

	
	$("#list1 li").remove();
	$("#list2 li").remove();			
	$("#list3 li").remove();
	
	var numVals = listResults.length;
	var colIndex1 = Math.floor(numVals/3);
	var colIndex2 = Math.floor(numVals*2/3);
	var colIndex3 = numVals - (colIndex1 + colIndex2);
	
	for (var i in listResults) {
	
		if (listResults.length <= 20) { 
	
			$("#list1").append(listResults[i]);
		
		} else { 
		
			if(i < colIndex1){
			
				$("#list1").append(listResults[i]); 
			
			} else if (i > colIndex1 && i < colIndex2) {
			
				$("#list2").append(listResults[i]); 
			
			} else {
			
				$("#list3").append(listResults[i]); 
			
			}
		}
	}	
		
	
}

function loadFiltResults(d,j,w) {
	var nm = ps[0];
	var bl = new Boolean(false);	
	var titleName = getTitleName(pre);
	var url = "http://www.freebase.com/api/service/mqlread";
	var q = '{"query": [{"'+nm+'":[{"name":"'+lsNm[j]+'"}],"name":null,"sort":"name","type":"/base/bioventurist'+ext+'"}]}';
	var v = gvNme[w];
	generalLoadQuery(q, url, bl, pre, spre);
	
	var sortTitle = '<h3 id="header3">' + titleName + ' filtered by: ' + v + ' (' +  lsNm[j] + ')</h3>';
	$("#header3").remove();
	$("#sort_title").append(sortTitle);
	document.getElementById('filtProps').selectedIndex = 0; 
	
}



function createListSearch(suggestNewText,qType,createType,prefix,searchText) {


	jQuery(function($) {

		var options = {

			soft: true,
			suggest_new: suggestNewText,
			ac_param: {
				type: qType
			}
		};

		$('#searchSuggestList').freebaseSuggest(options)

		.val(searchText)

		.bind('fb-select', function(e, data) { location.href = prefix + data.name; })

		.bind('fb-select-new', function(e, data) { 

			var topic_id = createTopic(data.name,createType);
			//console.dir(data); 
			jConfirm(data.name+' has been created.  Would you like to go edit?', 'Confirmation Dialog', function(r) {
				location.href = create_bvr_topic_href(prefix, topic_id);

			});

			//alert('Created ' + data.name +'. Click <html><body><a href="/company/'+data.name+'">here</a></body></html> to edit.');
			

			//location.href = prefix + data.name;
			})

		.blur(function(e) { if ($(this).val() == "") $(this).val(searchText); })

		.focus(function(e) { if ($(this).val() == searchText) $(this).val(''); });

	});

	

}

